import React from 'react';
import { Card, Table, Tag, Space, Select, Input, Button, message, Modal, Popover, Image, Form, Switch } from 'antd';

export default function MachineList() {
  const [group, setGroup] = React.useState('all');
  const [status, setStatus] = React.useState('all');
  const [keyword, setKeyword] = React.useState('');
  const [visibleCols, setVisibleCols] = React.useState(['userName','enableStatus','isDebug','isBlue','isHaptic','isSms']);
  const [selectedKeys, setSelectedKeys] = React.useState([]);
  const [editing, setEditing] = React.useState(null);
  const [openEdit, setOpenEdit] = React.useState(false);
  const [openConfig, setOpenConfig] = React.useState(false);
  const [openPayment, setOpenPayment] = React.useState(false);
  const [openMaps, setOpenMaps] = React.useState(false);
  const [openLineProduct, setOpenLineProduct] = React.useState(false);
  const [form] = Form.useForm();

  const allGroups = React.useMemo(() => ([
    { label: '全部分组', value: 'all' },
    { label: '华东一区', value: '华东一区' },
    { label: '华南一区', value: '华南一区' },
    { label: '西南一区', value: '西南一区' },
    { label: '华北一区', value: '华北一区' },
  ]), []);

  const [machines] = React.useState(() => ([
    {
      id: 'A1-001',
      name: '自动售货机 A1-001',
      group: '华东一区',
      status: 'online',
      location: '上海-徐汇',
      salesToday: 520,
      lastOnlineAt: '2025-10-01 12:10',
      userName: '张三',
      lockState: 0,
      faultNum: 2,
      stockOutNum: 1,
      stockAlertNum: 3,
      stockNormalNum: 20,
      stripeSubscriptionPayType: 1,
      rentState: 0,
      expireDate: '2025-12-01',
      isOutDateDays: 25,
      enableStatus: 1,
      isDebug: 0,
      isBlue: 1,
      isHaptic: 0,
      isSms: 1,
      twoCode: 'https://dummyimage.com/200x200/1890ff/ffffff.png&text=LYWLPZ',
    },
    {
      id: 'B3-210',
      name: '自动售货机 B3-210',
      group: '华东一区',
      status: 'offline',
      location: '',
      salesToday: 0,
      lastOnlineAt: '2025-10-01 09:01',
      userName: '李四',
      lockState: 1,
      faultNum: 1,
      stockOutNum: 2,
      stockAlertNum: 0,
      stockNormalNum: 15,
      stripeSubscriptionPayType: 0,
      rentState: 1,
      expireDate: '2025-10-15',
      isOutDateDays: -1,
      enableStatus: 0,
      isDebug: 1,
      isBlue: 0,
      isHaptic: 1,
      isSms: 0,
      twoCode: 'https://dummyimage.com/200x200/fa8c16/ffffff.png&text=LYWLPZ',
    },
    {
      id: 'C2-045',
      name: '自动售货机 C2-045',
      group: '华南一区',
      status: 'online',
      location: '广州-天河',
      salesToday: 430,
      lastOnlineAt: '2025-10-01 12:05',
      userName: '王五',
      lockState: 2,
      faultNum: 0,
      stockOutNum: 1,
      stockAlertNum: 2,
      stockNormalNum: 25,
      stripeSubscriptionPayType: 2,
      rentState: 0,
      expireDate: '2025-11-12',
      isOutDateDays: 40,
      enableStatus: 1,
      isDebug: 0,
      isBlue: 1,
      isHaptic: 1,
      isSms: 1,
      twoCode: 'https://dummyimage.com/200x200/67c23a/ffffff.png&text=LYWLPZ',
    },
  ]));

  const filtered = React.useMemo(() => {
    return machines.filter(m => {
      if (group !== 'all' && m.group !== group) return false;
      if (status !== 'all' && m.status !== status) return false;
      if (keyword && !(m.id + m.name + m.location).toLowerCase().includes(keyword.toLowerCase())) return false;
      return true;
    });
  }, [machines, group, status, keyword]);

  const rowSelection = {
    selectedRowKeys: selectedKeys,
    onChange: (keys) => setSelectedKeys(keys),
    getCheckboxProps: (record) => ({ disabled: record.status === 'offline' }),
  };

  const openAddressDialog = (record) => {
    setEditing(record);
    setOpenMaps(true);
  };

  const handleUnlock = (record) => {
    message.success(`已发送解锁指令：${record.name}`);
  };

  const proportionBar = (r) => {
    const total = Math.max(1, r.faultNum + r.stockOutNum + r.stockAlertNum + r.stockNormalNum);
    const w = (n) => Math.round((n / total) * 240);
    return (
      <div style={{ height: 34, display: 'flex', alignItems: 'center', color: '#fff', justifyContent: 'center' }}>
        <div onClick={() => message.info('故障数')} style={{ width: w(r.faultNum), height: 34, lineHeight: '34px', backgroundColor: '#555555', cursor: 'pointer', textAlign: 'center' }}>{r.faultNum}</div>
        <div onClick={() => message.info('无货数')} style={{ width: w(r.stockOutNum), height: 34, lineHeight: '34px', backgroundColor: '#E44D60', cursor: 'pointer', textAlign: 'center' }}>{r.stockOutNum}</div>
        <div onClick={() => message.info('缺货数')} style={{ width: w(r.stockAlertNum), height: 34, lineHeight: '34px', backgroundColor: '#F1C901', cursor: 'pointer', textAlign: 'center' }}>{r.stockAlertNum}</div>
        <div onClick={() => message.info('正常数')} style={{ width: w(r.stockNormalNum), height: 34, lineHeight: '34px', backgroundColor: '#09BB07', cursor: 'pointer', textAlign: 'center' }}>{r.stockNormalNum}</div>
      </div>
    );
  };

  const baseColumns = [
    { title: '设备编号', dataIndex: 'id', width: 120, sorter: (a,b)=>a.id.localeCompare(b.id) },
    { title: '设备名称', dataIndex: 'name', sorter: (a,b)=>a.name.localeCompare(b.name) },
    { title: '所属分组', dataIndex: 'group', width: 140 },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      render: (v) => (
        v === 'online' ? (
          <div style={{ display:'flex', justifyContent:'center', alignItems:'center' }}>
            <span style={{ width:10, height:10, background:'#67c23a', borderRadius:'50%' }} />
            <span style={{ marginLeft:5, color:'#67c23a', fontSize:13 }}>在线</span>
          </div>
        ) : (
          <div style={{ display:'flex', justifyContent:'center', alignItems:'center' }}>
            <span style={{ width:10, height:10, background:'#f56c6c', borderRadius:'50%' }} />
            <span style={{ marginLeft:5, color:'#f56c6c', fontSize:13 }}>离线</span>
          </div>
        )
      ),
    },
    {
      title: '地理位置',
      dataIndex: 'location',
      width: 200,
      render: (v, r) => v ? v : (
        <Button type="link" danger onClick={()=>openAddressDialog(r)}>Click here to Add Address</Button>
      ),
    },
  ];

  const optionalColumns = [
    { key:'userName', col: { title: '用户', dataIndex:'userName', width: 140 } },
    { key:'teamName', col: { title: '设备组名称', dataIndex:'group', width: 140 } },
    { key:'equipmentName', col: { title: '设备名', dataIndex:'name', width: 150 } },
    { key:'mqState', col: { title: '在线', dataIndex:'status', width: 90, render: (v)=> v==='online' ? (
      <div style={{ display:'flex', justifyContent:'center', alignItems:'center' }}>
        <span style={{ width:10, height:10, background:'#67c23a', borderRadius:'50%' }} />
        <span style={{ marginLeft:5, color:'#67c23a', fontSize:13 }}>在线</span>
      </div>
    ) : (
      <div style={{ display:'flex', justifyContent:'center', alignItems:'center' }}>
        <span style={{ width:10, height:10, background:'#f56c6c', borderRadius:'50%' }} />
        <span style={{ marginLeft:5, color:'#f56c6c', fontSize:13 }}>离线</span>
      </div>
    ) } },
    { key:'isLock', col: { title: '是否锁定', dataIndex:'lockState', width: 120, render: (_, r)=> (
      r.lockState===0 ? <span style={{ color:'#67c23a' }}>正常</span> : r.lockState===1 ? (
        <Tag color="error" onClick={()=>handleUnlock(r)} style={{ cursor:'pointer' }}>解锁</Tag>
      ) : <span style={{ color:'#f56c6c' }}>异常</span>
    ) } },
    { key:'faultNum', col: { title: '货道详情', dataIndex:'faultNum', width: 260, render: (_, r)=> proportionBar(r) } },
    { key:'subscription', col: { title: 'Subscription Status', dataIndex:'stripeSubscriptionPayType', width: 160, render: (v, r)=> (
      [1,2,'1','2'].includes(v) ? (
        <div className="active-subscription" onClick={()=>message.info(`Active 点击：${r.name}`)} style={{ color:'#67c23a', cursor:'pointer' }}>Active</div>
      ) : 'Not Started'
    ) } },
    { key:'renewal', col: { title: 'Renewal Date', dataIndex:'expireDate', width: 190, render: (_, r)=> (
      r.rentState===1 ? <span style={{ color:'#faad14' }}>Renewing</span> : (
        <span className={r.isOutDateDays <= 0 ? 'maturity' : ''}>{r.expireDate}</span>
      )
    ) } },
    { key:'enableStatus', col: { title: '启用状态', dataIndex:'enableStatus', width: 80, render: (v)=> v===1?'启用':'停用' } },
    { key:'isDebug', col: { title: '调试模式', dataIndex:'isDebug', width: 130, render: (v)=> v? '是':'否' } },
    { key:'isBlue', col: { title: '远程控制', dataIndex:'isBlue', width: 130, render: (v)=> v? '是':'否' } },
    { key:'isHaptic', col: { title: '感应控制', dataIndex:'isHaptic', width: 210, render: (v)=> v? '是':'否' } },
    { key:'isSms', col: { title: '短信告警', dataIndex:'isSms', width: 100, render: (v)=> v? '是':'否' } },
    { key:'salesToday', col: { title: '今日销售额', dataIndex:'salesToday', width: 140, align:'right', render: (v)=> `￥ ${Number(v).toLocaleString('zh-CN')}` } },
    { key:'lastOnlineAt', col: { title: '最近在线时间', dataIndex:'lastOnlineAt', width: 180 } },
  ];

  const operationColumn = {
    title: '操作',
    dataIndex: 'op',
    fixed: 'right',
    width: 360,
    render: (_, r) => (
      <div style={{ display:'flow-root' }}>
        <Button type="link" onClick={()=>{ setEditing(r); setOpenEdit(true); }}>编辑</Button>
        <Button type="link" onClick={()=>{ setEditing(r); setOpenLineProduct(true); }}>货道</Button>
        <Button type="link" onClick={()=>{ setEditing(r); setOpenPayment(true); }}>支付配置</Button>
        <Button type="link" onClick={()=> message.info(`保证金：${r.name}`)}>保证金</Button>
        <Popover placement="left" title="联网网络配置" content={<div style={{ width:200, textAlign:'center' }}><Image src={r.twoCode} width={200} /></div>} trigger="click">
          <Button type="link">联网配置</Button>
        </Popover>
        <Button type="link" onClick={()=>{ setEditing(r); setOpenMaps(true); }}>设备位置</Button>
        <Button type="link" onClick={()=> message.info(`一键配置：${r.name}`)}>一键配置</Button>
        <Button type="link" onClick={()=>{ setEditing(r); setOpenConfig(true); }}>详细配置</Button>
        <Button type="link" onClick={()=> message.info(`远程控制：${r.name}`)}>远程控制</Button>
      </div>
    ),
  };

  const columns = [
    ...baseColumns,
    ...optionalColumns.filter(o=> visibleCols.includes(o.key)).map(o=> o.col),
    operationColumn,
  ];

  return (
    <div style={{ display: 'grid', gap: 16 }}>
      <Card variant="borderless">
        <Space wrap>
          <Select options={allGroups} value={group} onChange={setGroup} style={{ width: 180 }} />
          <Select
            options={[
              { label: '全部状态', value: 'all' },
              { label: '在线', value: 'online' },
              { label: '离线', value: 'offline' },
            ]}
            value={status}
            onChange={setStatus}
            style={{ width: 160 }}
          />
          <Input value={keyword} onChange={(e) => setKeyword(e.target.value)} placeholder="搜索编号/名称/位置" style={{ width: 280 }} />
          <Select
            mode="multiple"
            value={visibleCols}
            onChange={setVisibleCols}
            style={{ minWidth: 260 }}
            placeholder="显示列"
            options={[
              { label:'用户', value:'userName' },
              { label:'设备组名称', value:'teamName' },
              { label:'设备名', value:'equipmentName' },
              { label:'在线', value:'mqState' },
              { label:'是否锁定', value:'isLock' },
              { label:'货道详情', value:'faultNum' },
              { label:'订阅状态', value:'subscription' },
              { label:'续费日期', value:'renewal' },
              { label:'启用状态', value:'enableStatus' },
              { label:'调试模式', value:'isDebug' },
              { label:'远程控制', value:'isBlue' },
              { label:'感应控制', value:'isHaptic' },
              { label:'短信告警', value:'isSms' },
              { label:'今日销售额', value:'salesToday' },
              { label:'最近在线时间', value:'lastOnlineAt' },
            ]}
          />
          <Button type="primary" onClick={() => message.success('刷新成功')}>刷新</Button>
          <Button onClick={() => { setGroup('all'); setStatus('all'); setKeyword(''); }}>重置</Button>
          <Button onClick={() => message.info(`批量续费：${selectedKeys.length} 项`)}>批量续费</Button>
          <Button onClick={() => message.info(`批量管理：${selectedKeys.length} 项`)}>批量管理</Button>
          <Button danger onClick={() => message.info(`恢复机器：${selectedKeys.length} 项`)}>恢复机器</Button>
        </Space>
      </Card>

      <Card title="机器清单" variant="borderless" styles={{ body: { paddingTop: 8 } }}>
        <Table
          rowKey={(r) => r.id}
          dataSource={filtered}
          columns={columns}
          rowSelection={rowSelection}
          pagination={{ pageSize: 8 }}
          onChange={(pagination, filters, sorter) => {
            // 模拟排序事件
            if (sorter && sorter.field) {
              message.info(`按 ${sorter.field} ${sorter.order === 'ascend' ? '升序' : '降序'}`);
            }
          }}
        />
      </Card>

      {/* 编辑弹窗 */}
      <Modal title="编辑设备" open={openEdit} onOk={()=>{ message.success('已保存（示例）'); setOpenEdit(false); }} onCancel={()=> setOpenEdit(false)}>
        <Form form={form} layout="vertical" initialValues={editing||{}}>
          <Form.Item name="name" label="设备名称"><Input /></Form.Item>
          <Form.Item name="location" label="地理位置"><Input /></Form.Item>
          <Form.Item name="enableStatus" label="启用"><Switch checkedChildren="启用" unCheckedChildren="停用" /></Form.Item>
        </Form>
      </Modal>

      {/* 配置弹窗 */}
      <Modal title="设备配置" open={openConfig} onOk={()=>{ message.success('配置已更新（示例）'); setOpenConfig(false); }} onCancel={()=> setOpenConfig(false)}>
        <div>这里放置详细配置项（示例）。</div>
      </Modal>

      {/* 支付配置 */}
      <Modal title="支付配置" open={openPayment} onOk={()=>{ message.success('支付配置已更新（示例）'); setOpenPayment(false); }} onCancel={()=> setOpenPayment(false)}>
        <div>卡机/投币器/纸币器配置（示例）。</div>
      </Modal>

      {/* 地图位置 */}
      <Modal title="设备位置" open={openMaps} onOk={()=> setOpenMaps(false)} onCancel={()=> setOpenMaps(false)}>
        <div>地址编辑或地图定位（示例）。</div>
      </Modal>

      {/* 货道配置 */}
      <Modal title="货道配置" open={openLineProduct} onOk={()=>{ message.success('货道已更新（示例）'); setOpenLineProduct(false); }} onCancel={()=> setOpenLineProduct(false)}>
        <div>货道商品/开关状态（示例）。</div>
      </Modal>
    </div>
  );
}